<?php

/**
 * Created by PhpStorm.
 * User: huqi
 * Date: 17/6/15
 * Time: PM5:01
 */

namespace App\Http\Controllers\backend ;

use App\Http\Controllers\Controller;
use Illuminate\Routing\RouteDependencyResolverTrait;
use Illuminate\Support\Facades\Request;
use Auth;

class Backend extends Controller
{
    use RouteDependencyResolverTrait ;
    private $controller = 'IndexController';
    private $method  = 'actionIndex';
    public $container ;
    public function __construct()
    {
        $this->container = app() ;
        //$this->middleware('auth.admin:admin');
    }

    public function init($slug = ''){
        $user = auth('admin')->user()->name;
        $slug = Request::getPathInfo() ;
        $slug = substr($slug,strlen('/backend/'));
        $this->formatSlug($slug) ;

        $className = 'App\\Http\\Controllers\\backend\\'.$this->controller ;
        $controller = new $className ;

        // 增加方法的依赖注入
        //$ref = new \ReflectionClass($controller) ;
        //$method = $ref->getMethod($this->method);
        //$params = $method->getParameters() ;
        $params = $this->resolveClassMethodDependencies([],$controller,$this->method) ;
        $called =  call_user_func_array([$controller , $this->method ],$params) ;

        if($called === true){
            return response()->json(['code' => 0]) ;
        }

        if(is_numeric($called)){
            return response()->json(['code' => $called]) ;
        }

        if($called instanceof \App\models\Base){
            return response()->json(['code' => 422 , 'error' => $called->getErrors()]);
        }

        return $called ;
    }

    public function formatSlug($slug){
        $slugs = explode("/",$slug) ;
        $slugs = array_filter($slugs);
        if(empty($slugs)){
            return ;
        }

        $len = count($slugs) ;

        if($len == 1){
            $this->controller = ucfirst($slugs[0]).'Controller' ;
            return ;
        }

        $this->method = 'action'.ucfirst(array_pop($slugs)) ;
        $contr = ucfirst(array_pop($slugs)).'Controller' ;

        $subNameSpace = '' ;
        if(!empty($slugs)){
            $subNameSpace = implode('\\',$slugs).'\\' ;
        }

        $this->controller = $subNameSpace.$contr ;
    }
}